package com.miao.server;

import com.miao.handler.WebsocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author <a href="https://gitee.com/a-tom-is-cry">Xing</a>
 * @Date 2024/9/7 16:06
 * @Description websocke启动端
 */
@Slf4j
@NoArgsConstructor
public class WebsocketSign implements Runnable {

    private WebsocketHandler websocketHandler = new WebsocketHandler();

    public Integer port = 8080;
    public String path = "/";

    /**
     * @param port 监听端口号
     */
    public WebsocketSign(Integer port) {
        this.port = port;
    }

    /**
     * @param port 监听端口号
     * @param path 访问路径
     */
    public WebsocketSign(Integer port, String path) {
        this.port = port;
        this.path = path;
    }

    /**
     * websocket初始化启动器，默认端口号：8080,访问路径：/
     */
    private void init() {
        NioEventLoopGroup boos = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boos, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //基于http的连接，需要http解码
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
                            //黏包
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            pipeline.addLast(new WebSocketServerProtocolHandler(path == null ? "/" : path));
                            pipeline.addLast(websocketHandler);
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .option(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("websocket服务端启动成功，监听端口：{},访问路径：{}", port, path == null ? "/" : path);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //优雅的关闭
            boos.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

    @Override
    public void run() {
        new WebsocketSign(port, path).init();
    }
}
